﻿using System;
using BrainTechLLC;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Threading;

namespace BrainTechLLC.Silverlight.ClientApplication
{
    public partial class DebugPanel : UserControl
    {
        public DebugInformation DebugInfo { get; set; }
        public bool HasBoundDebugInformation { get; set; }

        public DebugPanel()
        {
            InitializeComponent();
        }

        public void BindDebugInformation(DebugInformation debugInfo)
        {
            DebugInfo = debugInfo;
            debugInfo.PropertyChanged += new PropertyChangedEventHandler(debugInfo_PropertyChanged);
            ShowInfo(string.Empty);
        }

        public void ShowInfo(string prop)
        {
            if (string.IsNullOrEmpty(prop) || prop == "BytesSent")
                txtBytesSent.Text = DebugInfo.BytesSent.ToString();

            if (string.IsNullOrEmpty(prop) || prop == "BytesReceived")
                txtBytesReceived.Text = DebugInfo.BytesReceived.ToString();

        }

        void debugInfo_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            Dispatcher.BeginInvoke(() => ShowInfo(e.PropertyName));
        }
    }

    public class DebugInformation : INotifyPropertyChanged
    {
        public static DebugInformation _instance;

        public static DebugInformation Instance
        {
            get
            {
                if (_instance == null)
                {
                    Interlocked.CompareExchange<DebugInformation>(ref _instance, new DebugInformation(), null);
                }

                return _instance;
            }
        }

        public DebugInformation()
        {
            DataAccess.Communications.PropertyChanged += new PropertyChangedEventHandler(Communications_PropertyChanged);
        }

        public long BytesSent
        {
            get { return DataAccess.Communications.BytesSent; }
            set { }
        }

        public long BytesReceived
        {
            get { return DataAccess.Communications.BytesReceived; }
            set { }
        }

        void Communications_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            App.MainDispatcher.BeginInvoke(() => OnPropertyChanged(e.PropertyName));
        }

        public void OnPropertyChanged(string prop)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}